/*********************************************************************************
 *      Copyright:  (C) 2022 dairongan<2974932606@qq.com>
 *                  All rights reserved.
 *
 *       Filename:  get_temp.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(07/28/2022)
 *         Author:  dairongan <2974932606@qq.com>
 *      ChangeLog:  1, Release initial version on "07/28/2022 03:29:49 PM"
 *                 
 ********************************************************************************/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <dirent.h>
#include <time.h>
#include "logger.h"
#include "get_temp.h"

#define SHT20_PATH "/dev/sht20"

int get_temp_hum(float *temp_f,float *hum_f)
{
	int ret=0;
	int fd_sht20=0;
    unsigned short temp,hum;
    unsigned short databuf[2]={0};

	if(!temp_f||!hum_f)
	{
		log_error("the temp or hum argument is failure!\r\n");
		return -1;
	}

	fd_sht20 = open(SHT20_PATH, O_RDWR);
    if(fd_sht20 < 0)
    {
        log_error("open sht20 device file fail\r\n");
		close(fd_sht20);
        return -1;
    }

	ret = read(fd_sht20,&databuf,sizeof(databuf));
    if(ret==0)//数据读取成功
    {
        temp = databuf[0];
        hum = databuf[1];

        *temp_f = -46.85 + (175.72 * (temp / (float) 0xFFFF));
        *hum_f = -6.0 + (125.0 * (hum / (float) 0xFFFF));
    }else
    {
        log_error("read temperature and humidity failed!\r\n");//按下
		close(fd_sht20);
		return -1;
    }

	close(fd_sht20);
	return 0;
}

int sampling_timer(struct time_interval *sti)
{
    int     flag=0;
    time_t  now;

    now=time(NULL);

    if(now>=sti->last_time+sti->interval)
    {
        sti->last_time=now;
        flag=1;
    }
    return flag;

}
